import Taro from "@tarojs/taro";
import { sendValidCodeApi } from "../register/api";

export const useSendMsgCode = (state) => {
  const nextStep = () => {
    if (!state.accountForm.phone) {
      Taro.showToast({
        title: "请输入手机号",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    const paramsObj = {
      bizType: state.mode === "register" ? 1 : 2,
      phone: state.accountForm.phone,
    };
    sendValidCodeApi(paramsObj)
      .then(() => {
        Taro.showToast({
          title: "验证码已发送",
          icon: "none",
          duration: 2000,
        });
        state.surplus = 60;
        state.hasMsgCode = true;
        startCountdown(state);
      })
      .catch((err) => {
        Taro.showToast({
          title: err.data.msg,
          icon: "none",
          duration: 2000,
        });
      });
  };
  const startCountdown = () => {
    state.sign = setInterval(() => {
      if (state.surplus <= 0) {
        clearInterval(state.sign);
        state.surplus = -1;
        state.hasMsgCode = false;
        // const { phone } = state.accountForm;
        // state.accountForm = { phone };
      } else {
        state.surplus = state.surplus - 1;
      }
    }, 1000);
  };
  return () => (
    <tz-view class="preview">
      <tz-form>
        <tz-input
          v-model={state.accountForm.phone}
          placeholder="请输入手机号"
        />
      </tz-form>
      <tz-button class="next-btn" type="success" onClick={nextStep}>
        下一步
      </tz-button>
    </tz-view>
  );
};
